/*============================================================================
 PROJECT: TalkWrench
 FILE:    PickPhotoView.m
 AUTHOR:  Nguyen Minh Khoai
 DATE:    2/20/13
 =============================================================================*/

/*============================================================================
 IMPORT
 =============================================================================*/
#import "PickPhotoView.h"
#import "UIImage+Resize.h"
#import <AssetsLibrary/AssetsLibrary.h>

/*============================================================================
 PRIVATE MACRO
 =============================================================================*/

/*============================================================================
 PRIVATE INTERFACE
 =============================================================================*/
@interface PickPhotoView()
@property (nonatomic, strong)   UIPopoverController *popOverController;
@property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;
@property (weak, nonatomic) IBOutlet UIView *outlineView;

@end

@implementation PickPhotoView
@synthesize delegate;
@synthesize holderViewController;
@synthesize selectedImage;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        /* create queue */
        queue = [[NSOperationQueue alloc] init];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    /* create queue */
    queue = [[NSOperationQueue alloc] init];
    
    self.backgroundImageView.layer.cornerRadius = kCornerRadius;
}

+ (PickPhotoView *)sharedPickPhotoView {
    static PickPhotoView *sharedObj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(!sharedObj) {
            sharedObj = [[IBHelper sharedUIHelper] loadViewNib:@"PickPhotoView"];
        }
    });
    return sharedObj;
}

- (void)showImagePickerWithSource:(UIImagePickerControllerSourceType)source {
    if([UIImagePickerController isSourceTypeAvailable:source]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = source;
        picker.allowsEditing = YES;
        
        if (IS_IPAD) {
            UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:picker];
            [popover presentPopoverFromRect:CGRectMake(0, 200, 200, 0) inView:self permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
            self.popOverController = popover;
        }
        else{ // iPhone
            /* show picker on root controller */
            [holderViewController presentViewController:picker animated:YES completion:^{
                
            }];
        }
        
        /* hide pick photo view */
        [self hide];
    }
}

- (IBAction)didTouchedOnPickPhotoButton:(id)sender {
    UIButton *button = (UIButton *)sender;
    [self showImagePickerWithSource:(button.tag == 2 ?
                                     UIImagePickerControllerSourceTypePhotoLibrary : UIImagePickerControllerSourceTypeCamera)];
}

#pragma mark
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    /* store image in cache folder */
    self.selectedImage = [info valueForKey:UIImagePickerControllerEditedImage];
    
    [queue addOperationWithBlock:^{
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera ) {
            UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
            [library writeImageToSavedPhotosAlbum:image.CGImage
                                      orientation:(ALAssetOrientation)image.imageOrientation
                                  completionBlock:^(NSURL *assetURL, NSError *error ) {
                                      if(_getPhotoAssetURLCallback != NULL) {
                                          _getPhotoAssetURLCallback(assetURL);
                                      }
                                  }];
        } else {
            if(_getPhotoAssetURLCallback != NULL) {
                _getPhotoAssetURLCallback([info valueForKey:UIImagePickerControllerReferenceURL]);
            }
        }
    }];
    
    if(_pickerType == kPhotoPickerTypeAvatar) {
        /* store image in cache folder */
        [queue addOperationWithBlock:^{
            /* scale image */
            NSData *imageData = UIImageJPEGRepresentation(self.selectedImage, 1);
            [imageData writeToFile:[FileHelper avatarPath] atomically:YES];
        }];
    }
    
    /* dismiss picker photo */
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    if (IS_IPAD) { // dismiss Pop hover controller
        [self.popOverController dismissPopoverAnimated:YES];
    }
    
    CallTargetWith2Obj(delegate, @selector(imagePickerView:didPickedImage:), self, selectedImage);
    _completionCallback(selectedImage, NO);
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    if (IS_IPAD) { // dismiss Pop hover controller
        [self.popOverController dismissPopoverAnimated:YES];
    }
    
    _completionCallback(nil, YES);
}

- (void)showOnViewController:(UIViewController *)controller {
    
    /* don't show if visibling */
    if(visibling) {
        return;
    }
    visibling = YES;
    
    /* keep present view controller */
    self.holderViewController = controller;
    
    /* show if hidden view */
    if(!self.superview) {
        /* get top window */
        UIWindow    *topWindow = [UIApplication sharedApplication].keyWindow;
        self.outlineView.center = CGPointMake(topWindow.center.x, topWindow.center.y + [UIApplication sharedApplication].statusBarFrame.size.height/2);
        self.frame = CGRectMake(0, 0, topWindow.frame.size.width, topWindow.frame.size.height);
        [topWindow addSubview:self];
        _backgroundView.alpha = 0;
        
        /* scale view to 0.1 for preparing to zoom again */
        self.transform = CGAffineTransformMakeScale(0.1, 0.1);
        [UIView animateWithDuration:0.35f
                         animations:^{
                             self.transform = CGAffineTransformMakeScale(1, 1);
                         }
                         completion:^(BOOL finished) {
                             _backgroundView.alpha = 0.70;
                         }];
    }
}

- (void)showOnViewController:(UIViewController *)controller resultBlock:(PickPhotoViewCallback)callback {
    self.completionCallback = callback;
    [self showOnViewController:controller];
}

- (void)showOnViewController:(UIViewController *)controller
                     forType:(PhotoPickerType)type
                 resultBlock:(PickPhotoViewCallback)callback {

    self.pickerType = type;
    self.completionCallback = callback;
    [self showOnViewController:controller];
}

- (void)hide {
    /* don't hide if hidden */
    if(!visibling) {
        return;
    }
    visibling = NO;
    
    /* hide it */
    if (self.superview) {
        _backgroundView.alpha = 0;
        
        /* scale view to 0.1 for preparing to zoom again */
        [UIView animateWithDuration:0.35f
                         animations:^{
                             self.transform = CGAffineTransformMakeScale(0.1, 0.1);
                         }
                         completion:^(BOOL finished) {
                             self.transform = CGAffineTransformMakeScale(1, 1);
                             [self removeFromSuperview];
                         }];
    }
}

- (IBAction)didTouchedCancelButton:(id)sender {
    [self hide];
}

@end
